package cinema.service;

import cinema.model.*;
import cinema.util.*;
import java.util.*;

public class UserService {
    private static final Map<String, User> users = new HashMap<>();

    public static void initAdmin() {
        if (!users.containsKey("admin")) {
            users.put("admin", new AdminUser("1", "admin", "ynuinfo#777", "000"));
        }
    }

    public static User login(String username, String password) {
        User u = users.get(username);
        if (u != null && u.checkPassword(password)) {
            if (password.equals("123456")) {
                String newPwd = InputUtil.readLine("首次登录请修改密码: ");
                u.changePassword(newPwd);
            }
            return u;
        }
        return null;
    }

    public static void manageUsers(User admin) {
        while (true) {
            System.out.println("\n===用户管理===");
            System.out.println("1. 列出用户 2. 添加用户 3. 删除用户 4. 查询用户 5. 返回");
            switch (InputUtil.readInt("请选择: ")) {
                case 1 -> users.values().forEach(u ->
                        System.out.printf("%s %s %s %s %s\n", u.getId(), u.getUsername(), u.getType(), u.getPhone(), "注册时间省略"));
                case 2 -> {
                    String id = UUID.randomUUID().toString();
                    String username = InputUtil.readLine("用户名: ");
                    if (users.containsKey(username)) { System.out.println("用户名已存在"); break; }
                    String typeStr = InputUtil.readLine("类型(MANAGER/FRONT_DESK): ");
                    UserType type = UserType.valueOf(typeStr);
                    String phone = InputUtil.readLine("手机号: ");
                    users.put(username, type==UserType.MANAGER?
                            new ManagerUser(id, username, "123456", phone) :
                            new FrontDeskUser(id, username, "123456", phone));
                    Logger.log("添加用户", username);
                }
                case 3 -> {
                    String del = InputUtil.readLine("删除用户名: ");
                    if ("admin".equals(del)) { System.out.println("不能删除admin"); break; }
                    if (users.remove(del) != null) Logger.log("删除用户", del);
                }
                case 4 -> {
                    String q = InputUtil.readLine("查询用户名: ");
                    User u = users.get(q);
                    if (u != null) System.out.println(u.getUsername()+" "+u.getType()+" "+u.getPhone());
                }
                case 5 -> { return; }
            }
        }
    }

    public static User get(String username) { return users.get(username); }
}